package com.example.interceptor;

import com.example.entity.User;
import com.example.util.EhcacheUtil;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class cbmInterceptor implements HandlerInterceptor {

    //在请求处理之前进行调用
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {


        //统一校验用户是否登录，未登录或者超时状态返回对应标识
        try {
            String validateId = null;
            //如果validate 存在 说明当前用户是登录状态并且未超时
            validateId = httpServletRequest.getParameter("validateId");
            User user = (User) EhcacheUtil.getInstance().get("session",validateId);
            if(user != null) {
                return true;
            }
        }catch (Exception exception){
            System.out.print(exception.getMessage());
        }
        //用户请求异常，返回错误编码
        Map<String,String> map = new HashMap<>();
        map.put("code","-1");
        httpServletResponse.setCharacterEncoding("utf-8");
        PrintWriter printWriter = httpServletResponse.getWriter();
        printWriter.write(new Gson().toJson(map));
        printWriter.close();
        return false;
    }

    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    //在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
